"""Functions for determining line of sight"""

from pyre.core import types

def bresenham(world, start, goal):
    """
    bresenham(World, Coordinate, Coordinate): list of Coordinate
    Uses Bresenham's line drawing algorithm to draw a straight line from start
    to the goal, stopping on any obstacles.
    """

    dx = abs(goal[0] - start[0]) * 2
    dy = abs(goal[1] - start[1]) * 2
    ix = 1 if start[0] < goal[0] else -1
    iy = 1 if start[1] < goal[1] else -1

    x, y = start[0], start[1]
    path = [types.Coordinate(x, y)]

    if dx >= dy:
        error = dy - dx / 2
        while x != goal[0]:
            if error >= 0:
                y += iy
                error -= dx
            x += ix
            error += dy
            pos = types.Coordinate(x, y)
            path.append(pos)
            if not world.translucient_at(pos):
                break
    else: # dx < dy
        error = dx - dy / 2
        while y != goal[1]:
            if error >= 0:
                x += ix
                error -= dy
            y += iy
            error += dx
            pos = types.Coordinate(x, y)
            path.append(pos)
            if not world.translucient_at(pos):
                break

    return path
